import React from "react";
import { useNavigate } from "react-router-dom";
import useSWR from "swr";
import { fetcher } from "../utils";
import "./course.css";

function CourseList(props) {
    const navigate = useNavigate();
    const { data: courses, error } = useSWR("/api/course/list", fetcher);

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>课程信息列表</h3>
                <button className="btn" onClick={() => navigate("/course/new")}>
                    新建课程
                </button>
            </div>
            <div className="paper-body">
                <table className="table">
                    <thead>
                        <tr>
                            <th>课程号</th>
                            <th>课程名称</th>
                            <th>学分</th>
                            <th>学时</th>
                        </tr>
                    </thead>
                    <tbody>
                        {error && <tr><td colSpan="4">加载失败</td></tr>}
                        {!courses && !error && <tr><td colSpan="4">加载中...</td></tr>}
                        {courses && courses.length === 0 && <tr><td colSpan="4">暂无课程</td></tr>}
                        {courses && courses.map(cou => (
                            <tr key={cou.cou_sn}>
                                <td>{cou.cou_no}</td>
                                <td>{cou.cou_name}</td>
                                <td>{cou.credit}</td>
                                <td>{cou.hours}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

export default CourseList;
